package com.example.smartg.utils;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.example.smartg.HttpUtil;
import com.example.smartg.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import okhttp3.Call;
import okhttp3.Response;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.stick.AbsStickPackageHelper;
import tp.xmaihh.serialport.utils.ByteUtil;

public class GeGouUtil {
    public List<String> details;
    // 串口配置
    public SerialHelper serialHelper;
    public String SPORT_NAME = "/dev/ttyS4"; //串口路径
    //    public static String SPORT_NAME = "/dev/ttyUSB2"; //串口路径
    public int BAUD_RATE = 19200; //波特率
    public String error_msg;
    /**
     * 串口配置/接收返回的数据
     * （在哪调用这函数都行，只需放在打开串口之前就行了）
     */
    public void initSerialConfig() {
        //初始化SerialHelper对象，设定串口名称和波特率
        serialHelper = new SerialHelper(SPORT_NAME, BAUD_RATE) {
            @Override
            protected void onDataReceived(ComBean paramComBean) {
                Message message = mHandler.obtainMessage();
                message.obj = paramComBean;
                mHandler.sendMessage(message);
            }
        };

        /*
         * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
         * 我这里重新设定一个自适应数据位数的
         */
        serialHelper.setStickPackageHelper(new AbsStickPackageHelper() {
            @Override
            public byte[] execute(InputStream is) {
                try {
                    int available = is.available();
                    if (available > 0) {
                        byte[] buffer = new byte[available];
                        int size = is.read(buffer);
                        if (size > 0) {
                            return buffer;
                        }
                    } else {
                        SystemClock.sleep(50);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }
    //接收到的数据
    public Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            ComBean comBean = (ComBean) msg.obj;
            //获取数据
            String str = ByteUtil.ByteArrToHex(comBean.bRec);
            System.out.println(str);
            // 把电磁锁反馈返回服务器
            send_feedback_to_server(str,listToArray(details));
            // 根据反馈弹出提示框
            return false;
        }
    });
    //打开串口（先配置，再打开串口）
    public boolean openSerialHelper() {
        //已经打开串口了就不用再打开
        if (serialHelper.isOpen()) {
            Log.e("串口状态", "已经打开");
            return false;
        }
        //打开串口
        try {
            serialHelper.open();
            Log.e("串口状态", "打开");
        } catch (IOException e) {
            Log.e("串口状态", "关闭");
            e.printStackTrace();
        }

        return true;
    }
    //关闭串口（注销时候或手动关闭）
    public boolean closeSerialHelper() {
        if (!serialHelper.isOpen()) return false;
        serialHelper.close();
        return true;
    }
    private void open(String cmd_hex) {
        serialHelper.sendHex(cmd_hex); //十六进制数
    }
    public static void show(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.custrom_dialog);
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.custom_dialog, null);
        Button btn_sure = (Button) v.findViewById(R.id.dialog_btn_sure);
        Button btn_cancel = (Button) v.findViewById(R.id.dialog_btn_cancel);
        //builer.setView(v);//这里如果使用builer.setView(v)，自定义布局只会覆盖title和button之间的那部分
        final Dialog dialog = builder.create();
        dialog.show();
        dialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }
    public void send_feedback_to_server(String feedback, String[] detail) {
        String url = "http://10.2.47.115/smartg_api/check_auth_str";
        //实例化
        com.example.smartg.HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();

        try {
            json.put("auth_str", feedback);
            json.put("detals", detail);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("exception", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");

                    if (code == 20000) {
                        Log.e("接收sucess", msg);
                        String cmd = jsonObject.optString("data");
                    } else {
                        Log.e("接收error", msg);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public String[] listToArray(List<String> list) {
        String[] strings = list.toArray(new String[list.size()]);
        return strings;
    }
}
